import type { WebsiteTableField } from "@/assets/ts/websiteTableFieldsMap";
import { Button, message, Modal, Space, type TableColumnsType } from "ant-design-vue";
import { getCityOptionsApi, getKeywordTypeCityTypeApi } from "@/api/keyword";
import websiteTableFields from "@/assets/ts/websiteTableFieldsMap";
import { LinkSystemControlComponent, WebsiteAddLinkModalContent } from "@/components/home/tsx/websitesComponents";
import { toUrl } from "@/utils/common";
import fieldInTableColumnMap, { defaultColumns } from "@/assets/ts/websitesTableColumns";
import mainStore from "@/stores/main";
import { addWebsiteLinkApi } from "@/api/friendlyChain";
const $store = mainStore();
export function useColumns(showFields: Ref<Array<string>>) {
    const currentRow = ref({})
    const websiteShowDataVisible = ref(false)
    const firstColumns: TableColumnsType = [
        {
            dataIndex: "id",
            title: "网站ID",
            align: "center",
            width: 80,
            fixed: "left"
        },
        {
            dataIndex: "new_root_domain",
            title: "新根域名",
            width: 140,
            ellipsis: true,
            align: "center",
            fixed: "left",
        },
        {
            dataIndex: "pc_domain",
            title: "PC域名",
            align: "center",
            width: 140,
            fixed: "left",
            ellipsis: true,
        },
    ];
    const lastColumns: TableColumnsType = [
        {
            dataIndex: "action",
            title: "操作",
            width: 240,
            align: "center",
            fixed: "right",
            customRender: (row) => {
                const addLinkModel = h(Button, {
                    type: "link", onClick() {
                        if (!row.record.link_user) {
                            return message.error("找不到友链人!");
                        }
                        const addLinkParams = reactive({
                            linkuser_id: row.record.link_user,
                            edituser_id: $store.userInfo.id,
                            name: "",
                            url: "",
                            pc_domain: row.record.pc_domain,
                            type_id: -1,
                            prefix: "https://"
                        });
                        if (row.record.program_type === 10) {
                            addLinkParams.type_id = 0;
                        }
                        Modal.confirm({
                            title: "添加友链",
                            maskClosable: true,
                            content: h(WebsiteAddLinkModalContent, {
                                params: addLinkParams
                            }),
                            okText: "确定",
                            onOk() {
                                if (!addLinkParams.name || !addLinkParams.url) {
                                    message.error("请填写完整!");
                                    return;
                                }
                                if (addLinkParams.url.includes("http://") == false && addLinkParams.url.includes("https://") == false) {
                                    message.error("url缺少http://或者https://");
                                    return;
                                }
                                if (row.record.program_type === 10 && addLinkParams.type_id <= 0) {
                                    message.error("请选择分类!");
                                    return;
                                }
                                return addWebsiteLinkApi({ ...addLinkParams, url: addLinkParams.url })
                                    .then(() => {
                                        message.success("操作成功!");
                                    })
                                    .catch((e) => {
                                        message.error(e.response.data.msg || "操作失败!");
                                    });
                            }
                        });
                    }
                }, { default: () => "添加友链" })
                const LinkSystemControl = h(LinkSystemControlComponent, { row });
                const toPublishRuleView = h(
                    "a",
                    {
                        target: "_blank",
                        style: {
                            color: "#1677ff"
                        },
                        href: toUrl(`/esarticle/publish-rule/list?domain=${row.record.pc_domain}`)
                    },
                    { default: () => "发布规则" }
                );
                const showData = h(Button, {
                    type: "link",
                    onClick: () => {
                        currentRow.value = row.record
                        websiteShowDataVisible.value = true
                    }
                }, { default: () => "查看" })
                return h(Space, {}, { default: () => [showData, LinkSystemControl, addLinkModel] });
            }
        }
    ];
    // @ts-ignore
    const dataIndexs = firstColumns.map(item => item.dataIndex)
    return {
        columns: computed<TableColumnsType>(() =>
            firstColumns
                .concat(
                    showFields.value.filter(item => !dataIndexs.includes(item)).map(
                        (field) => fieldInTableColumnMap[field as WebsiteTableField] || defaultColumns(field as WebsiteTableField)
                    )
                )
                .concat(lastColumns)
        ),
        websiteShowDataVisible,
        currentRow
    }
}
export type CityOptions = {
    label: string;
    values: Array<string>;
};
export async function useCityOptions() {
    const result = await getCityOptionsApi();
    // @ts-ignore
    return result.data as Array<CityOptions>;
}
export async function useYunSonTypeOptions() {
    // 获取孕分类下的城市分类
    const result = await getKeywordTypeCityTypeApi();
    // @ts-ignore
    return result.data.data as SelectOption;
}
export function useGetWebsiteDomains(selectedRowKeys: Array<Record<string, number>>): Record<string, number> {
    const websiteDomains: Record<string, number> = {};
    for (const item of selectedRowKeys) {
        const key = Object.keys(item)[0];
        const value = Object.values(item)[0];
        websiteDomains[key] = value;
    }
    return websiteDomains;
}

export interface FieldOptionsObjType {
    [key: string]: {options:{ label: string; value: string }[],checkAll:boolean,isAllChecked:boolean};
}

export function useSelectFields() {
    const showFields = toRef($store, "websitesTableFields");
    const fieldGroup = [
        {
            group_name: "运维",
            data: [
                "apiv2",
                "id",
                "web_user",
                "link_user",
                "content_user",
                "website_type",
                "websitetype_child",
                "program_type",
                "adapt_type",
                "ad_website",
                "j_type",
                "jsc_type",
                "domain_account",
                "dns_account",
                "guoneiad_type",
                "shipei_type",
                "ad_type",
                "keywords_type",
                "content_type",
                "neilian_type",
                "seo_type",
                "es_type",
                "es",
                "benan",
                "website_group_type",
                "new_root_domain",
                "ad_type2",
                "domain",
                "m_domain",
                "pc_domain",
                "web_name",
                "target_kwd_count",
                "home_link_name",
                "copyright_info",
                "default_keyword",
                "site_description",
                "index_title",
                "buckname",
                "nip",
                "rds_name",
                "origin_ip",
                "origin_server_name",
                "load_balance",
                "cdn_ip",
                "cdn_server_name",
                "qz",
                "performance",
                "target_keyword_es_indexs",
                "unpublished_count",
                "public_ip",
                "last_update_public_ip",
                "rds_db_name",
                "web_template_name",
                "m_template_name",
                "nginx__name"

            ]
        },
        {
            group_name: "蜘蛛",
            data: [
                "baidu_spider_pc",
                "baidu_spider_mobile",
                "baidu_spider_pc_render",
                "baidu_spider_mobile_render",
            ]
        },
        {
            group_name: "排名",
            data: [
                "baidu_tendency",
                "b_tagnum",
                "new_baidu",
                "new_baidu_first",
                "new_baidu_kdy",
                "ranging_up_down",
                "new_baidu_subject",
                "new_baidu_core",
                "new_baidu_corepc",
                "new_baidupc",
                "new_sogou",
                "new_toutiao",
                "new_biying",
                "new_google",
                "new_baidu_rise",
                "new_baidu_decline",
                "new_baidupc_decline",
                "new_baidupc_rise",
                "ranking_sogou",
                "new_sogou_core",
                "s_jscnum",
                "sogou_tendency",
                "s_tagnum",
                "ranking_toutiao",
                "toutiao_core",
                "t_jscnum",
                "toutiao_tendency",
                "t_tagnum",
                "ranking_biying",
                "biying_core",
                "by_jscnum",
                "biying_tendency",
                "by_tagnum",
                "ranking_google",
                "google_core",
                "gg_jscnum",
                "google_tendency",
                "gg_tagnum",
                "baidu_soulu",
                "sogou_soulu"
            ]
        },
        {
            group_name: "文章+tag",
            data: [
                "article_num_yesterday",
                "article_num_all",
                "tag_num",
                "yesterday_count",
                "article_sum",
                "multiple_choice_field1",
                "multiple_choice_field2",
                "multiple_choice_field3",
            ]
        },
        {
            group_name: "统计",
            data: [
                "es_plan_publish_num",
                "es_yesterday_publish_success_num",
                "es_yesterday_publish_error_num",
                "visit_num",
                "search_engine_referrer_visit_num",
                "visit_user_num",
                "trigger_num",
                "last_two_weeks_baidu_trigger",
                "last_two_weeks_baidu_visit",
                "last_two_weeks_toutiao_trigger",
                "last_two_weeks_toutiao_visit",
                "last_two_weeks_google_trigger",
                "last_two_weeks_google_visit",
                "last_two_weeks_other_search_engine_trigger",
                "last_two_weeks_other_search_engine_visit",
                "last_one_week_baidu_trigger",
                "last_one_week_baidu_visit",
                "last_one_week_toutiao_trigger",
                "last_one_week_toutiao_visit",
                "last_one_week_google_trigger",
                "last_one_week_google_visit",
                "last_one_week_other_search_engine_trigger",
                "last_one_week_other_search_engine_visit",
            ]
        },
        {
            group_name: "百度收录",
            data: [
                'm_domain_site',
                'pc_domain_site',
                'root_domain_site',
                'fan_domain_site',
                'baidu_site_update_at',
            ]
        },
        {
            group_name: "外链(友链+内链)",
            data: [
                "link_num",
                "outer_link_count",
                "outer_link_count_update_at",
                "external_link_num",
                "link_store_link_num"
            ]
        },
        {
            group_name: "动态外链",
            data: [
                "m_index_export_dynamic_link_num", 
                "pc_index_export_dynamic_link_num", 
                "m_column_export_dynamic_link_num",
                "pc_column_export_dynamic_link_num",
                "m_article_export_dynamic_link_num",
                "pc_article_export_dynamic_link_num",
                "m_import_dynamic_link_domain_num",
                "pc_import_dynamic_link_domain_num",
                "dynamic_link_data_update_at",
            ]
        }
    ];
    // @ts-ignore
    const fieldOptions = Object.keys(websiteTableFields).map((key) => ({ label: websiteTableFields[key], value: key }));
    let fieldOptionsGroupObj: FieldOptionsObjType = reactive({  });

    for (const option of fieldOptions) {
        let isFiled = true;
        for (const item of fieldGroup) {
            if (item["data"].includes(option["value"])) {
                if(item["group_name"] in fieldOptionsGroupObj){
                    fieldOptionsGroupObj[item["group_name"]]["options"].push(option)
                }else{
                    fieldOptionsGroupObj[item["group_name"]] = {
                        "options":[option],
                        "checkAll":false,
                        "isAllChecked":false,
                    }
                }
                isFiled = false;
                break;
            }
        }
        if (isFiled) {
            if("其他" in fieldOptionsGroupObj){
                fieldOptionsGroupObj["其他"]["options"].push(option)
            }else{
                fieldOptionsGroupObj["其他"] = {
                    "options":[option],
                    "checkAll":false,
                    "isAllChecked":false,
                }
            }
        }
    }
    return {
        fieldOptionsGroupObj,
        showFields,
        fieldOptions
    };
}
